package com.jt.safe.extension


import com.jt.safe.R
import com.jt.safe.base.BaseActivity
import com.jt.safe.config.BaseApplication
import com.jt.safe.exception.HubException
import com.jt.safe.state.ViewState
import java.lang.reflect.ParameterizedType
import java.net.ConnectException
import java.net.UnknownHostException


/**
 * 获取vm clazz
 */
@Suppress("UNCHECKED_CAST")
fun <VM> getVmClazz(obj: Any): VM {
    return (obj.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as VM
}


/**
 * 显示页面状态
 * @param viewState 接口返回值
 * @param onLoading 加载中
 * @param onSuccess 成功回调
 * @param onError 失败回调
 *
 */
fun <T> BaseActivity<*>.parseState(
    viewState: ViewState<T>,
    onSuccess: (T?) -> Unit,
    onError: ((HubException) -> Unit)? = null,
    onLoading: (() -> Unit)? = null,
    onCode: ((T?, Int) -> Unit)? = null,
    onErrorCode: (() -> Unit)? = null
) {
    when (viewState) {
        is ViewState.Loading -> {
            showProgress()
            onLoading?.run { this }
        }
        is ViewState.Success -> {
            dismissProgress()
            onSuccess(viewState.data)
            onCode?.let { it(viewState.data, viewState.int) }
        }
        is ViewState.Error -> {
            dismissProgress()
            if (viewState.int == 30001) {
                onErrorCode?.let { it() }
            } else {
                showToast(viewState.error.message)
            }
            onError?.run { this(viewState.error) }
        }
    }
}


/**
 *
 */
fun Throwable?.parseErrorString(): String {
    return when (this) {
        is ConnectException -> BaseApplication.INSTANCE.getString(R.string.ConnectException)
        is UnknownHostException -> BaseApplication.INSTANCE.getString(R.string.UnknownHostException)
        else -> BaseApplication.INSTANCE.getString(R.string.ElseNetException)
    }
}

